<template>
  <view class="flex-1">
    <view
      class="text-theme font-bold text-xl mx-auto text-center mb-6 mt-[56rpx]"
      v-if="info.score_user"
      >{{ info.score_user.name }}</view
    >
    <view class="pl-[52rpx] flex items-center mt-[78rpx] mb-6">
      <view class="text-xl font-bold text-[#303133]">性别：</view>
      <view class="aaaa">
        <uni-data-select
          disabled
          :clear="false"
          v-model="state.sex"
          :localdata="range"
          @change="change"
        ></uni-data-select
      ></view>
    </view>
    <view class="px-3">
      <view
        class="flex items-center bg-[#4365DE] rounded-[40rpx] px-[44rpx] text-xl font-bold text-white mb-[52rpx]"
      >
        <view class="leading-[56rpx] py-[12rpx] w-1/4">项目</view>
        <view class="leading-[56rpx] py-[12rpx] w-1/2 text-center"
          >成绩录入</view
        >
        <view class="leading-[56rpx] py-[12rpx] w-1/4 text-right">得分</view>
      </view>
    </view>
    <view class="px-[42rpx]">
      <view class="mt-[36rpx]" v-for="(a, idx) in list" :key="idx">
        <view class="px-[10rpx] flex flex-col" v-if="a.name">
          <view class="flex items-center mb-[14rpx]">
            <view class="w-2 h-2 bg-[#B3B6BD]"></view>
            <view class="pl-[20rpx] font-bold text-xl text-[#303133]">{{
              a.name
            }}</view>
          </view>
          <!--
          <view class="flex items-center bbbb">
            <view class="pr-3 text-[#303133] text-base">
              {{ a.list.length }}选1输入：</view
            >
            <uni-data-select
              v-if="a?.project"
              :clear="false"
              disabled
              v-model="a.project"
              :localdata="a.list"
            ></uni-data-select>
          </view>
					-->
        </view>
        <template v-for="(item, index) in a.list" :key="index">
          <view
            class="flex items-center justify-between text-xl font-bold text-black px-[10rpx] pb-[10rpx]"
            :class="{
              line: index == a.list.length - 1 && idx == list.length - 1,
            }"
            v-if="a.project == item.score_id"
          >
            <view class="py-[12rpx] font-bold w-[202rpx]">
              <view class="text-[#606266] text-xl">{{
                item.project_name
              }}</view>
              <!-- <view
                v-if="item.values"
                class="text-[#AFAFAF] leading-[56rpx] text-base"
                >{{ item.show_unit }}</view
              > -->
            </view>
            <view
              class="leading-[56rpx] py-[12rpx] flex flex-1 items-end justify-center w-1/2"
            >
              <!-- <template v-for="(v, i) in item.show_unit" :key="v"> -->
              <view class="w-[285rpx]">
                <input
                  class="iiiii"
                  placeholderClass="hhhhh"
                  type="digit"
                  @input="(e) => handleScore(item, item.values, idx, index, i)"
                  v-model="item.values"
                  :placeholder="item.show_unit + '，如' + item.show_val"
                  border="bottom"
                />
              </view>
              <!-- <text class="px-[12rpx]"> {{ v.name }}</text> -->
              <!-- </template> -->
            </view>
            <view class="leading-[56rpx] py-[12rpx] w-1/4 text-right">{{
              item.socre || "0"
            }}</view>
          </view>
        </template>
      </view>
    </view>
    <view class="mt-[56rpx]">
      <view
        class="flex justify-between items-center text-xl font-bold text-black px-[52rpx] mb-[40rpx]"
      >
        <view>总得分</view>
        <view
          >{{ info.level.score_total ? info.level.score_total : "无" }}
        </view>
      </view>
      <view
        class="flex justify-between items-center text-xl font-bold text-black px-[52rpx] mb-[80rpx]"
      >
        <view>评级</view>
        <view>{{ info.level.level_name ? info.level.level_name : "无" }} </view>
      </view>
      <view class="px-[38rpx] flex justify-between pb-[30rpx]">
        <view
          @click="changeTab(0)"
          :class="active === 0 ? 'active' : 'bor'"
          class="w-[190rpx] h-[72rpx] leading-[72rpx] text-center font-bold text-xl rounded-lg"
        >
          计算成绩
        </view>
        <view
          @click="changeTab(1)"
          :class="active === 1 ? 'active' : 'bor'"
          class="w-[190rpx] h-[72rpx] leading-[72rpx] text-center font-bold text-xl rounded-lg"
        >
          保存成绩
        </view>
        <view class="w-[190rpx] h-[72rpx] relative">
          <button
            v-if="info.open_kf == 1"
            open-type="contact"
            :class="active === 2 ? 'active' : 'bor'"
            class="w-full h-[72rpx] leading-[72rpx] text-center font-bold text-xl rounded-lg"
          >
            一键咨询
          </button>
          <view
            v-else
            @click="changeTab(2)"
            :class="active === 2 ? 'active' : 'bor'"
            class="w-full h-[72rpx] leading-[72rpx] text-center font-bold text-xl rounded-lg"
          >
            一键咨询
          </view>
        </view>
      </view>
    </view>
    <view class="px-5">
      <view class="mt-[14rpx] text-[#303133] text-[36rpx] font-bold">
        <view class="bbb pb-[20rpx]"> 提高方案 </view>
      </view>
      <view
        class="mt-[102rpx] flex flex-col w-full items-center pb-[128rpx]"
        v-if="info?.score_user?.feedback_status == 1"
      >
        <image src="@/static/timer.png" class="w-[184rpx] h-[184rpx]"></image>
        <view class="mt-[40rpx] text-xs text-[#D5D5D5] font-bold">待反馈</view>
      </view>
      <view
        v-if="info?.score_user?.feedback_status == 2"
        class="mt-[60rpx] pb-[128rpx]"
      >
        <view class="flex items-center mb-[40rpx]">
          <image
            :src="info.score_user.teacher.icon_image"
            class="w-[84rpx] h-[84rpx] rounded-full"
          ></image>
          <view class="pl-[34rpx] text-[#606266] text-base leading-[45rpx]">
            <view>{{ info.score_user.teacher.teacher_name }}</view>
            <view>{{ info.score_user.teacher.school }}</view>
          </view>
        </view>
        <up-parse :content="info.score_user.feedback_content"></up-parse>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { throttle, debounce } from "lodash";
import {
  getScoreDetail_api,
  calScoreItem_api,
  saveScore_api,
  questionOnce_api,
  calScoreTotal_api,
} from "@/api/index.js";
import uniDataSelect from "@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import { ref, reactive, computed } from "vue";
import { useUserStore } from "@/stores/user.js";
import { onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
const userStore = useUserStore();
const settingInfo = computed(() => userStore.setting);
const value = ref(1);
const range = ref([
  { value: 1, text: "男" },
  { value: 2, text: "女" },
]);

const state = reactive({
  sex: 1,
  id: "",
  score_type: "",
  area_id: "",
});

const active = ref(0);
const show = ref(false);
onShareAppMessage(() => {
  return {
    title: "钧韬竞速",
    path: `/pages/index/index`,
  };
});
onShareTimeline(() => {
  return {
    title: "钧韬竞速",
    query: `/pages/index/index`,
  };
});
const change = (e) => {
  state.sex = e;
  getList();
};
const changeTab = (index) => {
  // active.value = index;
  if (!index) return calcScore();
  if (index == 1) {
    // if (!info.value.level_code)
    //   return uni.showToast({
    //     title: "请先计算成绩",
    //     icon: "none",
    //   });
    const data = {
      scores: list.value
        .reduce((a, b) => {
          a.push(...b.list);
          return a;
        }, [])
        .map((e) => {
          return {
            sport_score_id: e.score_id, //评分项目ID
            point: e.socre || 0, //得分
            score: e.point || 0, //成绩，如果单位代码是ms时，需要将其转为分钟数提交，支持浮点类型
            unit: e.unit, //单位代码
          };
        }),
      score_total: info.value.score, //总评分
      area_id: state.area_id, //地区ID
      score_type: state.score_type, //类别
      sex: state.sex, //性别
      teacher_id: info.value.score_user?.teacher.id,
    };
    console.log(data);
    saveScore_api(data).then((res) => {
      console.log(res);
      uni.showModal({
        title: "温馨提示",
        content: "你的本次成绩已保存",
        icon: "none",
        showCancel: false,
        success: () => {},
      });
    });
    return;
  }
  if (index == 2) {
    questionOnce_api(state.id).then((res) => {
      console.log(res);
      uni.showModal({
        title: "温馨提示",
        content: "咨询已处理,请查看",
        showCancel: false,
        success: () => {
          getList();
        },
      });
    });
  }
};

const calcScore = () => {
  uni.showLoading({
    title: "正在计算...",
  });
  const num = list.value
    .reduce((a, b) => {
      a.push(...b.list);
      return a;
    }, [])
    .reduce((acc, cur) => {
      return acc * 1 + (cur.socre * 1 || 0);
    }, 0);
  console.log(num);
  info.value.score = num;
  calScoreTotal_api({
    score_total: num,
    area_id: state.area_id,
    score_type: state.score_type,
    sex: state.sex,
    scores: list.value
      .reduce((a, b) => {
        a.push(...b.list);
        return a;
      }, [])
      .map((e) => {
        return {
          sport_score_id: e.score_id, //评分项目ID
          point: e.socre || 0, //得分
          score: e.point || 0, //成绩，如果单位代码是ms时，需要将其转为分钟数提交，支持浮点类型
          unit: e.unit, //单位代码
        };
      }),
  })
    .then((res) => {
      console.log(res);
      info.value.level.level_code = res.level_code;
      info.value.level.level_name = res.level_name;
      info.value.level.score_total = res.score_total;
      info.value.score_user = { ...info.value.score_user, ...res };
      uni.hideLoading();
    })
    .finally(() => {});
};

const fomtrTimeToOrge = (item) => {
  if (item.unit == "ms") {
    if (item.name == "秒") {
      return formatMinutesToMinSec(item.value).sec;
    }
    if (item.name == "分") {
      return formatMinutesToMinSec(item.value).min;
    }
  }
};
const formatMinutesToMinSec = (minutes: number) => {
  const totalSeconds = Math.floor(minutes * 60);
  const min = Math.floor(totalSeconds / 60);
  const sec = totalSeconds % 60;

  return {
    min,
    sec,
  };
};
const list = ref([]);
const info = ref({
  score: "",
  open_kf: "",
  level: {
    level_code: "",
    level_name: "",
    score_total: "",
  },
});
const getList = (id) => {
  getScoreDetail_api(state.id).then((res) => {
    info.value = {
      ...res,
      score: res.score_user.score_total,
    };
    state.area_id = res.score_user.area_id;
    state.sex = res.score_user.sex;
    list.value = res.items.map((e) => {
      console.log(e);
      return {
        ...e,
        project: e.list.length && e.list[0].score_id,
        list: e.list.map((b) => {
          return {
            ...b,
            socre: b.point,
            point: b.score,
            values: b.score,
            text: b.project_name,
            value: b.score_id,

            // unit_name: b.unit_name.map((a) => {
            //   return {
            //     value:
            //       b.unit == "ms"
            //         ? fomtrTimeToOrge({
            //             name: a,
            //             value: b.score,
            //             unit: b.unit,
            //           }) || ""
            //         : b.score || "",
            //     name: a,
            //   };
            // }),
          };
        }),
      };
    });
    console.log(list.value, "    list.value");
  });
};

const fomtrTime = (item) => {
  if (item.name == "秒") {
    return item.value * 1;
  }
  if (item.name == "分") {
    return item.value * 60;
  }
};

const formatMin = (ms) => {
  return ms / 60;
};

const handleScore = debounce((item, value, idx, index, i) => {
  // console.log(item, value, idx, index, i);
  if (!value) {
    list.value[idx].list[index].socre = "0";
    list.value[idx].list[index].point = 0;
    return;
  }

  item.point = value;
  calScoreItem_api({
    score_id: item.score_id,
    score: value || 0,
  }).then((res) => {
    console.log(res);
    list.value[idx].list[index].socre = res.point;
    console.log(list.value, "list.valuelist.value");
  });
}, 600);

onLoad(({ id, type }) => {
  state.id = id;
  state.score_type = type;
  getList();
});
</script>

<style lang="scss">
.bbbb {
  :deep(.uni-select) {
    min-width: 260rpx !important;
    border-radius: 16rpx;
    padding-left: 24rpx;
    .uni-select__input-text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 700;
      font-size: 32rpx;
      color: #303133;
    }
    .uni-icons {
      font-size: 36rpx !important;
    }
  }
}

.aaaa {
  :deep(.uni-select) {
    width: 178rpx !important;
    border-radius: 16rpx;
    padding-left: 24rpx;
    .uni-select__input-text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 700;
      font-size: 32rpx;
      color: #303133;
    }
    .uni-icons {
      font-size: 36rpx !important;
    }
  }
}
:deep(.u-border-bottom) {
  border-bottom: 2rpx solid #000000 !important;
}
.line {
  padding-bottom: 56rpx;
  border-bottom: 2rpx solid #d1d1d1;
}

.active {
  background-color: #3889ff;
  color: #fff;
}

.bor {
  color: #000000;
  background-color: #fff;
  border: 2rpx solid #3889ff;
}
:deep(.u-input) {
  padding-left: 4rpx !important;
  padding-right: 4rpx !important;
  padding-bottom: 6rpx !important;
}
.bbb {
  border-bottom: 2rpx solid #d1d1d1;
}
:deep(.hhhhh) {
  font-weight: 500;
  font-size: 26rpx;
  color: #afafaf;
  line-height: 56rpx;
}
.iiiii {
  padding-left: 4rpx !important;
  padding-right: 4rpx !important;
  padding-bottom: 6rpx !important;
  font-size: 32rpx !important;
  border-bottom: 2rpx solid #000000 !important;
}
</style>
